/**
 * 通用报表界面重构版
 *
 */
import React from 'react';
import connect from 'react-redux/es/connect/connect';
import AdvancedTable from 'components/advanced-table';
import { messages } from 'share/common';
import UniversalReportService from './universal-report.service';
import ReportPrivateService from './report-private.service';
import ExportModal from 'components/template/export-modal/export-modal';
import SlideFrame from 'components/slide-frame';
import CustomExportSetting from 'containers/data-center/report/universal-report/components/custom-export-setting/custom-export-setting';
import { Button, Spin, Tooltip, Dropdown, Icon, Menu, Modal, message } from 'antd';
import 'styles/data-center/report/universal-report/index.scss';
import ReportFieldsEditor from '../travel-report/components/report-fields-editor';
import Condition from 'components/condition';
import errorMessage from 'share/errorMessage';
import CustomExportSettingService from 'containers/data-center/report/universal-report/components/custom-export-setting/custom-export-setting.service';

const { If } = Condition;
const ButtonGroup = Button.Group;

function mapStateToProps(state) {
  const { language, currentMenuPermission = {} } = state.main;
  const { company, tenant } = state.login;
  const { currentActiveKey = [] } = currentMenuPermission;
  const currentRoute = currentActiveKey[currentActiveKey.length - 1];
  return {
    language,
    currentRoute,
    tenant,
    company,
    currentMenuPermission: currentMenuPermission.currentMenu || {}
  };
}

function InitStateFactory() {
  return {
    exportSettings: [], //导出设置列表
    reportId: undefined,
    loadingCollection: {
      loadingSearchArea: true
    },
    fieldsEditorVisible: false, // 字段编辑modal是否可见
    pagination: {
      current: 1,
      page: 0,
      total: 0,
      pageSize: 20,
      showTotal: () => undefined // task 35260
    },
    searchForm: [],
    criteria: {}, // 当前搜索的参数
    columns: [],
    dataColumnsModal: [], // 字段编辑的columns
    reportDetail: {},
    tableData: [], // 当前表格数据
    currentReportPrivate: {}, // 各报表私有配置的载体
    methodCollection: {}, // 用来保存各报表私有的方法
    reportPrivateState: {}, // 各报表私有的state
    extraParams: {
      // 用于保存额外的路由参数，在当前页面间来回跳时并不会刷新，请注意，参考审批效率报表12跳转审批效率明细报表13
      isPreview: false
    }
  };
}

@connect(mapStateToProps)
class UniversalReport extends React.Component {
  advancedTableRef = undefined;

  state = InitStateFactory();

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { currentRoute } = this.props;
    this.setState({
      extraParams: {
        isPreview: currentRoute === 'universal-report-preview'
      }
    });
    this.init();
    this.getExportSetting();
  }

  getExportSetting = (id) => {
    if ((id || this.props.params.id) === '13' && !window.location.href.includes('universal-report-preview')) {
      CustomExportSettingService.getAllSettings({ reportId: 13 }).then((res) => {
        this.setState({ exportSettings: res.data });
      });
    }
  };

  // 存在从报表A跳转到报表B，这时需要刷新state（extraParams不刷新），然后再获取数据
  componentWillReceiveProps(nextProps) {
    if (nextProps.params.id !== this.props.params.id) {
      this.advancedTableRef.clearCache();
      const { extraParams } = this.state;
      this.resetState(extraParams);
      this.getExportSetting(nextProps.params.id);
    }
  }

  resetState = (extraParams) => {
    const newState = InitStateFactory();
    if (extraParams) {
      newState.extraParams = extraParams;
    }
    this.setState(newState, this.init);
  };

  init = () => {
    this.initPrivate();
    // 初始化searchArea
    this.initSearchArea().then(() => {
      // 触发第一次搜索
      // 需要在currentReportPrivate中开启
      if (this.state.currentReportPrivate.initSearch) {
        this.advancedTableRef.advancedSearchRef.search();
      }
    });
  };

  initPrivate = () => {
    const { params } = this.props;
    const { id: reportId } = params;
    const currentReportPrivate = ReportPrivateService[reportId] || {};
    const { reportPrivateState } = currentReportPrivate;
    let methodCollection = {};
    if (currentReportPrivate.methodCollectionFactory) {
      methodCollection = currentReportPrivate.methodCollectionFactory(this);
    }
    // 设置表单私有的配置
    this.setState({
      reportId,
      currentReportPrivate,
      methodCollection,
      reportPrivateState
    });
  };

  initSearchArea = async () => {
    const { params, language } = this.props;
    try {
      const res = await UniversalReportService.getReportDetail({
        reportId: params.id,
        context: this,
        langCode: language.code
      });
      const { data: reportDetail } = res;
      const { searchForm, columns, dataColumnsModal } = reportDetail;
      const { loadingCollection } = this.state;
      loadingCollection.loadingSearchArea = false;
      this.setState({
        reportDetail,
        loadingCollection,
        searchForm,
        columns,
        dataColumnsModal
      });
    } catch (e) {
      console.warn(e);
    }
  };

  getReportList = async (page, size, params) => {
    try {
      const { currentReportPrivate = {}, reportId, extraParams, pagination } = this.state;
      const { isPreview } = extraParams;
      const { extraSearch } = currentReportPrivate;
      const transferResult = await UniversalReportService.searchParamsTransfer({
        params,
        reportId,
        context: this
      });
      const requestBody = {
        id: reportId,
        page,
        size,
        preview: isPreview,
        criteria: transferResult
      };
      this.setState({
        criteria: transferResult
      });

      // 同时执行自定义报表额外搜索
      if (extraSearch) {
        extraSearch({ requestBody, context: this });
      }

      return UniversalReportService.getTravelDataList(requestBody).then((res) => {
        pagination.total = Number(res.headers['x-total-count']);
        pagination.current = page + 1;
        this.setState({
          tableData: res.data,
          pagination
        });
        return res;
      });
    } catch (err) {
      if (err && err.type === 'validateError') {
        // message.warn(err.message)
      } else {
        errorMessage(err ? err.response : err);
      }
      return Promise.reject();
    }
  };

  toggleFieldsEditorVisible = () => {
    const { fieldsEditorVisible } = this.state;
    this.setState({
      fieldsEditorVisible: !fieldsEditorVisible
    });
  };

  // 保存当前编辑之后的报表字段并刷新
  saveReportFields = (dataColumnsModal) => {
    this.toggleFieldsEditorVisible();
    this.setState(
      {
        dataColumnsModal
      },
      () => {
        this.initSearchArea().then(() => {
          // 触发第一次搜索
          // 但其实初始的搜索不一定是用户想要看到的，所以还是注释掉了
          // this.advancedTableRef.advancedSearchRef.search()
        });
      }
    );
  };

  onChangePagination = (changePagination) => {
    const { pagination } = this.state;
    const keys = ['current', 'page', 'pageSize', 'total'];
    keys.forEach((key) => {
      pagination[key] = changePagination[key];
    });
    this.setState({
      pagination
    });
  };

  //返回到列表
  handleBack = () => {
    window.history.go(-1);
  };

  // 渲染各报表私用区域（介于search和table之间）
  renderPrivateArea = () => {
    const { currentReportPrivate } = this.state;
    if (currentReportPrivate.renderChildren) {
      return currentReportPrivate.renderChildren(this);
    }
    return <div />;
  };

  renderMenu = () => {
    const { exportSettings } = this.state;
    return (
      <Menu onClick={this.handleOpenSetting}>
        {exportSettings.map((set) => {
          return (
            <Menu.Item key={set.id}>
              <div className="export-menu-pop">
                <div className={'title'}>
                  <span>{set.settingName}</span>
                </div>
                <div className={'icons-area'}>
                  <Tooltip title={<span>{messages('common.edit') /*编辑*/}</span>}>
                    <Icon type="edit" className="edit-icon" onClick={(e) => {}} />
                  </Tooltip>
                  <Tooltip title={<span>{messages('common.delete') /*删除*/}</span>}>
                    <Icon
                      type="delete"
                      className="delete-icon"
                      onClick={(e) => {
                        this.deleteSetting(e, set.id, set.settingName);
                      }}
                    />
                  </Tooltip>
                </div>
              </div>
            </Menu.Item>
          );
        })}
        <Menu.Item key="new">
          <div style={{ textAlign: 'left' }}>
            <Icon type="plus" /> {messages('finance-7.key353')/*新建导出设置*/}
          </div>
        </Menu.Item>
      </Menu>
    );
  };

  deleteSetting = (e, id, name) => {
    e.stopPropagation();
    e.preventDefault();
    Modal.confirm({
      title: messages('common.info') /*提示*/,
      content: messages('finance-7.key354',{arg1: name})/*确定删除【{arg1}】?*/,
      onOk: () => {
        CustomExportSettingService.deleteSingleExportSetting(id).then((res) => {
          message.success(messages('common.delete.successful') /*删除成功*/);
          this.getExportSetting();
        });
      }
    });
  };

  handleOpenSetting = (e) => {
    if (e.key === 'new') {
      this.openSlideFrame(messages('finance-7.key353')/*新建导出设置*/, { id: 'new', reportId: this.props.params.id });
    } else {
      this.openSlideFrame(messages('finance-7.key355')/*编辑导出设置*/, { id: e.key, reportId: this.props.params.id });
    }
  };

  //打开侧拉 编辑 外部报表
  openSlideFrame = (title, data) => {
    SlideFrame.open(
      {
        title,
        width: '800px',
        afterClose: (needRefresh) => {
          this.getExportSetting();
        },
        params: data,
        content: CustomExportSetting,
        hasFooter: true
      },
      this
    );
  };

  // 字段设置及导出数据
  renderUtils = () => {
    const {
      reportDetail,
      criteria,
      pagination,
      reportId: id,
      tableData,
      fieldsEditorVisible,
      dataColumnsModal,
      extraParams,
      exportSettings
    } = this.state;
    const { currentMenuPermission } = this.props;
    const { toggleFieldsEditorVisible, saveReportFields } = this;
    const { isPreview } = extraParams;
    const { page, pageSize: size } = pagination;
    const reportSearchDTO = {
      id,
      page,
      size,
      criteria
    };
    const disabled = currentMenuPermission.operationType === 'R';
    const menu = this.renderMenu();

    return (
      <div className="resize-table-utils">
        <section>
          <If value={!window.location.href.includes('universal-report-preview')}>
            <ExportModal
              settingList={exportSettings}
              chooseExportSet={this.props.params.id === '13' && !window.location.href.includes('universal-report-preview')}
              methodCheck
              codeCheck
              disabled={!tableData.length}
              type={'btn'}
              btnType={'primary'}
              exportTitle={messages('finance-7.key193') /*导出数据*/}
              exportType="REPORT"
              exportCondition={{
                exportType: 'REPORT',
                reportSearchDTO,
                command: reportDetail.reportCode
              }}
            />
          </If>
          <If value={this.props.params.id === '13' && !window.location.href.includes('universal-report-preview')}>
            <Dropdown overlay={menu} trigger={['click']} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
              <Button style={{ marginLeft: 8 }}>
                {messages('finance-7.key356')/*导出设置*/}
                <Icon type="down" />
              </Button>
            </Dropdown>
          </If>
        </section>
        <ButtonGroup>
          <ReportFieldsEditor
            visible={fieldsEditorVisible}
            onClose={toggleFieldsEditorVisible}
            fields={dataColumnsModal}
            onSave={saveReportFields}
            isPreview={isPreview}
          />
          <Tooltip
            title={<span style={{ whiteSpace: 'nowrap' }}>{messages('finance-7.key276') /*字段设置*/}</span>}
            placement="topLeft"
          >
            <Button icon="setting" disabled={disabled} onClick={this.toggleFieldsEditorVisible} />
          </Tooltip>
        </ButtonGroup>
      </div>
    );
  };

  render() {
    const { columns, searchForm, loadingCollection, reportDetail, pagination } = this.state;
    const { reportName = messages('finance-7.key301') /*报表*/ } = reportDetail;
    const tableName = `universal-report-${this.props.params.id}`;
    const hideUtil = ['table-utils'];
    return (
      <div className="universal-report-container">
        <Spin spinning={loadingCollection.loadingSearchArea}>
          <div className="full-height-page">
            <AdvancedTable
              title={reportName}
              columns={columns}
              searchForm={searchForm}
              service={this.getReportList}
              onRef={(ref) => (this.advancedTableRef = ref)}
              tableName={tableName}
              notLoadWhenMount
              waterMark
              hide={hideUtil}
              onChangePagination={this.onChangePagination}
              pagination={pagination}
              footer={
                <Button type="default" onClick={this.handleBack}>
                  {messages('common.back') /*返回*/}
                </Button>
              }
            >
              <div>
                {this.renderPrivateArea()}
                {this.renderUtils()}
              </div>
            </AdvancedTable>
          </div>
        </Spin>
      </div>
    );
  }

  static contextTypes = {
    router: React.PropTypes.object
  };
}

export default UniversalReport;
